﻿using GeoBox.AzureWeb.Models;
using GeoBox.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace GeoBox.AzureWeb.Controllers.API
{
    public class DeviceController : ApiController
    {
        private readonly GpsBoxEntities db = new GpsBoxEntities();

        public IEnumerable<ApiDevice> Get()
        {
            var now = DateTime.Now.ToUniversalTime();        
            return db.Devices.ToList().Select(x => new ApiDevice
            {
                Device = x,
                HasGpsSignal = (now - x.LastLocation.UtcTime).TotalMinutes <= 1,
                IsOnline = (now - x.UtcLastContact).TotalMinutes <= 1
            });
        }

        [HttpPost]
        public void Post(Device device)
        {
            var dev = db.Devices.Find(device.Id);
            if (device.LastLocation != null)
            {
                device.LastLocation.Device = dev;
                dev.GpsPoints.Add(device.LastLocation);
                dev.LastLocation = device.LastLocation;
                dev.UtcLastContact = device.LastLocation.UtcTime;
            }
            else
                dev.UtcLastContact = DateTime.Now.ToUniversalTime();
            db.SaveChanges();
        }


        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
